#Copyright 2008, 2009 Daniele Trainini

#This file is part of dmote.

#dmote is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License version 2.0 as published
#by the Free Software Foundation

#dmote is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with dmote.  If not, see <http://www.gnu.org/licenses/>.

import keycapture
import globalui
from socket import *

global sock
global ca
sock = socket(AF_BT, SOCK_STREAM, BTPROTO_RFCOMM)

def selector(sock, fas):
    head = fas.readline()
    lista = []
    data = fas.readline()
    while data.strip("\n") != ":END:":
        lista.append(unicode(data.strip("\n")))
        data = fas.readline()

    tosend = globalui.global_popup_menu(lista, unicode(head.strip("\n")))
    sock.send(repr(tosend))

def capturer(key):
    if key==keycapture.EKey1:
        sock.send(repr("1"))

    if key==keycapture.EKey2:
        sock.send(repr("2"))

    if key==keycapture.EKey3:
        sock.send(repr("3"))

    if key==keycapture.EKey4:
        sock.send(repr("4"))

    if key==keycapture.EKey5:
        sock.send(repr("5"))

    if key==keycapture.EKey6:
        sock.send(repr("6"))

    if key==keycapture.EKey7:
        sock.send(repr("7"))

    if key==keycapture.EKey8:
        sock.send(repr("8"))

    if key==keycapture.EKey9:
        ca.keys = ()#ricordarsi l'invio da inserire
        tosend = raw_input()
        print tosend
        sock.send(tosend)

    if key==keycapture.EKey0:
        sock.send(repr("0"))


addr, services = bt_discover()
print "DISCOVERED::"
if services.has_key('dmote'):
    print "dmote found"
    port = services['dmote']
else:
    print "merda"
			
sock.connect((addr, port))


ca=keycapture.KeyCapturer(capturer)
ca.forwarding=0
ca.keys=(keycapture.EKey1,keycapture.EKey2, keycapture.EKey3, keycapture.EKey4, keycapture.EKey5, keycapture.EKey6, keycapture.EKey7, keycapture.EKey8, keycapture.EKey9, keycapture.EKey0)

ca.start()

fas = sock.makefile('rb')
while(True):
    data = fas.readline()
    if data.strip("\n") == ":SELECT:":
        selector(sock, fas)
    elif data.strip("\n") == ":QUIT:":
        break
    else:
        print data,
        
ca.stop()
    
